#include <stdio.h>

#include <driver/uart.h>
#include "../glue_bridge.h"

int32_t halUartAvailableBytes(int32_t uart_num);

bridge_packet_t *halBridgeFetchPacket(
    int32_t uart_num)
{
    bridge_packet_t *packet = (bridge_packet_t *)malloc(sizeof(bridge_packet_t));
    uint8_t buff[4];

    if (halUartAvailableBytes(uart_num) == 0)
    {
        packet->opCode = OP_CODE_MIN;
        packet->dataSize = 0;
        packet->data = NULL;
        return packet;
    }

    memset(buff, 0, 4);
    uart_read_bytes(uart_num, &buff[0], 2, 100);
    packet->opCode = U16LE(buff);

    memset(buff, 0, 4);
    uart_read_bytes(uart_num, &buff[0], 4, 100);
    packet->dataSize = U32LE(buff);

    packet->data = (uint8_t *)malloc(packet->dataSize);
    uart_read_bytes(uart_num, packet->data, packet->dataSize, 100);

    return packet;
}

void halBridgeResponse(int32_t uart_num, bridgr_response_t *response)
{
    char buff[4];

    buff[0] = response->magic;
    buff[1] = response->resultType;
    uart_write_bytes(uart_num, buff, 2);

    LEU32(buff, response->dataSize);
    uart_write_bytes(uart_num, buff, 4);

    uart_write_bytes(uart_num, (char *)response->data, response->dataSize);
}